let baseUrl = 'https://qianzi.goldsu.cn';
export default class Api {
  defaultHeaders = {}
  setDefaultHeaders(headers) {
    this.defaultHeaders = headers;
  }

  addDefaultHeader(key, value) {
    this.defaultHeaders[key] = value;
  }

  removeDefaultHeader(key) {
    delete this.defaultHeaders[key];
  }

  get(url, params, header) {
    return this.request(url, "GET", params, header);
  }

  post(url, params, header) {
    return this.request(url, "POST", params, header);
  }

  request(url = '', method = 'GET', params = {}, header = {}) {
    return new Promise((resolve, reject) => {
      let reqUrl;
      if (url.startsWith('http') || url.startsWith('https')) {
        reqUrl = url;
      } else {
        reqUrl = baseUrl + url;
      }
      let token = wx.getStorageSync('token')
      let body = {
        url: reqUrl,
        data: params,
        method: method,
        timeout: 30 * 1000,
        responseType: 'text',
        header: {
          // 默认值
          // "XX-Device-Type": "wxapp",
          // "XX-Token": token,
          ...this.defaultHeaders,
          ...header
        },
        success(res) {
          // console.log("请求成功：", reqUrl,res)
          resolve(res.data)
          if (res.data.code == 401) {
            wx.removeStorageSync('token');
            wx.showToast({
              title: '请登录',
              icon: 'none'
            })
            setTimeout(() => {
              wx.reLaunch({
                url: '/pages/user/index',
              })
            }, 500);
          }
        },
        fail: (res) => {
          // console.log("请求失败：",reqUrl,res)
          reject(res.data)
        }
      }
      // console.log("发送请求：",reqUrl,body)
      try {
        wx.request(body)
      } catch (e) {
        console.log(e)
        reject(res);
      }

    });
  }
}